package net.howson.phil.datahiding.stream;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author howsonph
 * 
 */
public class NibbleInputStream extends InputStream {

	private final InputStream delegate;
	private int [] parts = new int[2];
	private int cursor = parts.length;
	
	public NibbleInputStream(InputStream delegate) {
		this.delegate = delegate;
	}

	@Override
	public int read() throws IOException {
		if (cursor<parts.length) {
			return parts[cursor++];
		} else {
			if (readData()) {
				return parts[cursor++];
			}
		}
		return -1;
	}

	private boolean readData() throws IOException {
		int data = delegate.read();
		if (data==-1) {		
			return false;
		}
		
		parts[0] = (data & 0xF0)>>>4;
		parts[1] = (data & 0x0F);
		cursor = 0;
		return true;
	}
	@Override
	public void close() throws IOException {
		delegate.close();
		super.close();
	}
	

}
